<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">车间</label>
        <el-select v-model="query.facility" clearable placeholder="车间" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery">
          <el-option v-for="item in facilitys" :key="item.id" :label="item.facilityname" :value="item.facility" />
        </el-select>
        <label class="el-form-item-label">班次名称</label>
        <el-input v-model="query.shiftName" clearable placeholder="班次名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">工时类型</label>
        <el-input v-model="query.hoursType" clearable placeholder="工时类型" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="车间" prop="facility">
            <el-select v-model="form.facility" style="width: 370px;" filterable>
              <el-option v-for="item in facilitys" :key="item.id" :label="item.facilityname" :value="item.facility" />
            </el-select>
          </el-form-item>
          <el-form-item label="班次名称" prop="shiftName">
            <el-input v-model="form.shiftName" style="width: 370px;" />
          </el-form-item>
          <div v-for="(item, index) in form.children" :key="index">
            <el-form-item label="工时类型" :prop="'children.'+index+'.hoursType'">
              <el-select v-model="item.hoursType" placeholder="请选择">
                <el-option
                  v-for="items in dict.hours_type"
                  :key="items.id"
                  :label="items.label"
                  :value="items.value"
                />
              </el-select>
              <el-link v-if="index === form.children.length-1" icon="el-icon-circle-plus-outline" @click="addChildren">新增</el-link>
              <el-link v-if=" form.children.length>1" @click="deleteChildren(index)">删除<i class="el-icon-delete" /> </el-link>
            </el-form-item>
            <el-form-item label="时间范围">
              <el-col :span="11">
                <el-form-item :prop="'children.'+index+'.startTime'">
                  <el-time-picker v-model="item.startTime" style="width: 100%;" placeholder="开始时间" arrow-control />
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2" style="width: 2%;">-</el-col>
              <el-col :span="11">
                <el-form-item :prop="'children.'+index+'.endTime'">
                  <el-time-picker v-model="item.endTime" style="width: 100%;" placeholder="结束时间" arrow-control />
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item label="计入工时" :prop="'children.'+index+'.isBillable'">
              <el-radio v-for="items in dict.hours_status" :key="items.id" v-model="item.isBillable" :label="items.value">{{ items.label }}</el-radio>
            </el-form-item>
          </div>
          <el-form-item label="状态" prop="status">
            <el-radio v-for="item in dict.shift_status" :key="item.id" v-model="form.status" :label="item.value">{{ item.label }}</el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        :row-key="rowKeyFunc"
        node-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" :selectable="selectable" />
        <el-table-column prop="facility" label="车间" />
        <el-table-column prop="shiftName" label="班次" />
        <el-table-column prop="hoursType" label="工时类型">
          <template slot-scope="scope">
            {{ dict.label.hours_type[scope.row.hoursType] }}
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" />
        <el-table-column prop="endTime" label="结束时间" />
        <el-table-column prop="isBillable" label="是否计入工时">
          <template slot-scope="scope">
            {{ dict.label.hours_status[scope.row.isBillable] }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            {{ dict.label.shift_status[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','shift:edit','shift:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              v-if="scope.row.hasOwnProperty('children')"
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudShift from '@/api/system/shift'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { getFacilitys } from '@/api/system/facility'

const defaultForm = { id: null, facility: null, shift: null, shiftName: null, hoursType: null, startTime: null, endTime: null, isBillable: null, status: null }
export default {
  name: 'Shift',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['hours_type', 'hours_status', 'shift_status'],
  cruds() {
    return CRUD({ title: '系统：班次', url: 'api/shift', idField: 'id', sort: 'id,desc', crudMethod: { ...crudShift }})
  },
  data() {
    return {
      facilitys: [],
      permission: {
        add: ['admin', 'shift:add'],
        edit: ['admin', 'shift:edit'],
        del: ['admin', 'shift:del']
      },
      rules: {
        facility: [
          { required: true, message: '车间不能为空', trigger: 'blur' }
        ],
        shiftName: [
          { required: true, message: '班次名称不能为空', trigger: 'blur' }
        ],
        // hoursType: [
        //   { required: true, message: '工时类型不能为空', trigger: 'blur' }
        // ],
        // startTime: [
        //   { required: true, message: '开始时间不能为空', trigger: 'blur' }
        // ],
        // endTime: [
        //   { required: true, message: '结束时间不能为空', trigger: 'blur' }
        // ],
        // isBillable: [
        //   { required: true, message: '是否计入工时不能为空', trigger: 'blur' }
        // ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'facility', display_name: '车间' },
        { key: 'shiftName', display_name: '班次名称' },
        { key: 'hoursType', display_name: '工时类型' },
        { key: 'startTime', display_name: '开始时间' },
        { key: 'endTime', display_name: '结束时间' },
        { key: 'isBillable', display_name: '是否计入工时' },
        { key: 'status', display_name: '状态' }
      ]
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.getFacility()
      return true
    },
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.handleDateTime(form)
      return true
    },
    [CRUD.HOOK.beforeToAdd](crud, form) {
      this.handleAddData(form)
      return true
    },
    [CRUD.HOOK.beforeDelete](crud, form) {
      this.deleteShiftData(form)
    },
    rowKeyFunc(row) {
      return String(row.id)
    },
    getFacility() {
      getFacilitys({ enabled: true }).then(res => {
        const facilityList = res.content
        this.bulidFacility(facilityList)
        this.facilitys = facilityList
      }).catch(() => {})
    },
    bulidFacility(facilityList) {
      facilityList.forEach(data => {
        data.facilityname = data.facility + '-' + data.facilityname
      })
    },
    handleDateTime(form) {
      form.children.forEach(data => {
        const date = new Date()
        const year = date.getFullYear()
        const month = date.getMonth() + 1
        const day = date.getDate()
        const startHour = data.startTime.split(':')[0]
        const startMinutes = data.startTime.split(':')[1]
        const startSeconds = data.startTime.split(':')[2]
        const endHour = data.endTime.split(':')[0]
        const endMinutes = data.endTime.split(':')[1]
        const endSeconds = data.endTime.split(':')[2]
        data.startTime = new Date(year, month, day, startHour, startMinutes, startSeconds)
        data.endTime = new Date(year, month, day, endHour, endMinutes, endSeconds)
        data.isBillable = data.isBillable.toString()
      })
      this.form.status = form.status.toString()
    },
    handleAddData(form) {
      this.form.children = []
      this.addChildren()
    },
    addChildren() {
      this.form.children.push({
        hoursType: '',
        startTime: '',
        endTime: '',
        isBillable: ''
      })
    },
    deleteChildren(index) {
      this.form.children.splice(index, 1)
    },
    selectable(row, index) {
      if (row.hasOwnProperty('children')) {
        return true
      }
      return false
    },
    deleteShiftData(data) {
      const ids = []
      if (data.length >= 1) {
        data.forEach(val => {
          val.children.forEach(childVal => {
            ids.push(childVal.id)
          })
        })
      } else {
        data.children.forEach(childVal => {
          ids.push(childVal.id)
        })
      }
      crudShift.del(ids)
    }
  }
}
</script>

<style scoped>

</style>
